// 配置管理模块 - 基于EMQX官方最佳实践
class ConfigManager {
    constructor() {
        this.configKey = 'mqtt_control_panel_config';
        this.defaultConfig = {
            mqtt: {
                // 浏览器环境推荐使用WebSocket协议
                brokerUrl: 'ws://broker.emqx.io:8083/mqtt',
                username: '',
                password: '',
                clientId: 'mqtt_web_client_' + Math.random().toString(16).substr(2, 8),
                keepalive: 60, // 心跳间隔(秒)
                clean: true,   // 清理会话
                reconnectPeriod: 1000, // 重连间隔(毫秒)
                connectTimeout: 4000   // 连接超时(毫秒)
            },
            commands: [
                {
                    buttonText: '指令1',
                    topic: '/869298058908310_act',
                    payload: '{"k":"AA_8D","v":"AA 00 00 00 00 00 00 8D"}',
                    qos: 0 // QoS级别: 0-最多一次, 1-至少一次, 2-正好一次
                },
                {
                    buttonText: '指令2',
                    topic: '/123456789/act',
                    payload: '{"k":"YAN","v":"f1_1_2"}',
                    qos: 0
                },
                {
                    buttonText: '指令3',
                    topic: '/123456789/act',
                    payload: '{"k":"YAN","v":"f1_1_3"}',
                    qos: 0
                }
            ]
        };
        this.init();
    }

    init() {
        // 加载配置或使用默认配置
        this.loadConfig();
        this.bindEvents();
        this.populateForm();
    }

    loadConfig() {
        const savedConfig = localStorage.getItem(this.configKey);
        if (savedConfig) {
            try {
                this.config = JSON.parse(savedConfig);
            } catch (e) {
                console.error('配置解析错误，使用默认配置:', e);
                this.config = {...this.defaultConfig};
            }
        } else {
            this.config = {...this.defaultConfig};
        }
    }

    saveConfig() {
        try {
            localStorage.setItem(this.configKey, JSON.stringify(this.config));
            return true;
        } catch (e) {
            console.error('保存配置失败:', e);
            return false;
        }
    }

    bindEvents() {
        // MQTT配置表单提交
        const mqttForm = document.getElementById('mqtt-config-form');
        if (mqttForm) {
            mqttForm.addEventListener('submit', (e) => {
                e.preventDefault();
                this.saveMqttConfig();
            });
        }

        // 测试连接按钮
        const testBtn = document.getElementById('test-connection');
        if (testBtn) {
            testBtn.addEventListener('click', () => {
                this.testConnection();
            });
        }

        // 保存指令配置按钮
        const saveCommandsBtn = document.getElementById('save-commands');
        if (saveCommandsBtn) {
            saveCommandsBtn.addEventListener('click', () => {
                this.saveCommandsConfig();
            });
        }
    }

    populateForm() {
        // 填充MQTT配置表单
        if (this.config.mqtt) {
            const brokerUrlInput = document.getElementById('broker-url');
            const usernameInput = document.getElementById('username');
            const passwordInput = document.getElementById('password');
            const clientIdInput = document.getElementById('client-id');
            const keepaliveInput = document.getElementById('keepalive');
            const timeoutInput = document.getElementById('timeout');

            if (brokerUrlInput) brokerUrlInput.value = this.config.mqtt.brokerUrl || '';
            if (usernameInput) usernameInput.value = this.config.mqtt.username || '';
            if (passwordInput) passwordInput.value = this.config.mqtt.password || '';
            if (clientIdInput) clientIdInput.value = this.config.mqtt.clientId || '';
            if (keepaliveInput) keepaliveInput.value = this.config.mqtt.keepalive || 60;
            if (timeoutInput) timeoutInput.value = this.config.mqtt.connectTimeout || 4000;
        }

        // 填充指令配置表单
        if (this.config.commands) {
            this.config.commands.forEach((command, index) => {
                const buttonTextInput = document.querySelector(`input[name="buttonText${index + 1}"]`);
                const topicInput = document.querySelector(`input[name="topic${index + 1}"]`);
                const payloadInput = document.querySelector(`textarea[name="payload${index + 1}"]`);

                if (buttonTextInput) buttonTextInput.value = command.buttonText || '';
                if (topicInput) topicInput.value = command.topic || '';
                if (payloadInput) payloadInput.value = command.payload || '';
            });
        }
    }

    saveMqttConfig() {
        const brokerUrl = document.getElementById('broker-url').value.trim();
        const username = document.getElementById('username').value.trim();
        const password = document.getElementById('password').value.trim();
        const clientId = document.getElementById('client-id').value.trim();
        const keepalive = parseInt(document.getElementById('keepalive').value) || 60;
        const connectTimeout = parseInt(document.getElementById('timeout').value) || 4000;

        if (!brokerUrl) {
            this.showStatus('请输入MQTT Broker地址', 'error');
            return;
        }

        // 验证协议格式
        const validProtocols = ['mqtt://', 'mqtts://', 'ws://', 'wss://'];
        const hasValidProtocol = validProtocols.some(protocol => brokerUrl.startsWith(protocol));
        if (!hasValidProtocol) {
            this.showStatus('Broker地址格式错误，请使用mqtt://, mqtts://, ws://或wss://开头', 'error');
            return;
        }

        this.config.mqtt = {
            brokerUrl,
            username,
            password,
            clientId: clientId || 'mqtt_web_client_' + Math.random().toString(16).substr(2, 8),
            keepalive: Math.max(10, Math.min(300, keepalive)), // 限制在10-300秒之间
            clean: true,
            reconnectPeriod: 1000,
            connectTimeout: Math.max(1000, Math.min(10000, connectTimeout)) // 限制在1-10秒之间
        };

        if (this.saveConfig()) {
            this.showStatus('MQTT配置保存成功', 'success');
        } else {
            this.showStatus('保存失败，请检查浏览器设置', 'error');
        }
    }

    saveCommandsConfig() {
        const commands = [];
        
        for (let i = 1; i <= 3; i++) {
            const buttonText = document.querySelector(`input[name="buttonText${i}"]`).value.trim();
            const topic = document.querySelector(`input[name="topic${i}"]`).value.trim();
            const payload = document.querySelector(`textarea[name="payload${i}"]`).value.trim();

            commands.push({
                buttonText: buttonText || `指令${i}`,
                topic,
                payload
            });
        }

        this.config.commands = commands;

        if (this.saveConfig()) {
            this.showStatus('指令配置保存成功', 'success');
        } else {
            this.showStatus('保存失败，请检查浏览器设置', 'error');
        }
    }

    async testConnection() {
        const brokerUrl = document.getElementById('broker-url').value.trim();
        const username = document.getElementById('username').value.trim();
        const password = document.getElementById('password').value.trim();

        if (!brokerUrl) {
            this.showStatus('请输入MQTT Broker地址', 'error');
            return;
        }

        this.showStatus('正在测试连接...', 'info');

        try {
            // 动态加载MQTT.js
            await this.loadMQTT();
            
            // 根据EMQX最佳实践配置连接选项
            const options = {
                clientId: 'test_client_' + Math.random().toString(16).substr(2, 8),
                clean: true,
                connectTimeout: 4000,
                keepalive: 30,
                reconnectPeriod: 0, // 测试时不自动重连
                protocolVersion: 4 // MQTT v3.1.1
            };

            // 处理认证信息
            if (username) {
                options.username = username;
                if (password) {
                    options.password = password;
                }
            }

            // 处理TLS/SSL连接的安全选项
            if (brokerUrl.startsWith('mqtts://') || brokerUrl.startsWith('wss://')) {
                options.rejectUnauthorized = false; // 允许自签名证书
            }

            const client = mqtt.connect(brokerUrl, options);

            return new Promise((resolve) => {
                const timeout = setTimeout(() => {
                    client.end(true); // 强制断开连接
                    this.showStatus('连接超时，请检查网络和Broker地址', 'error');
                    resolve(false);
                }, 8000); // 延长超时时间以适应TLS握手

                client.on('connect', (packet) => {
                    clearTimeout(timeout);
                    const protocolInfo = this.getProtocolInfo(brokerUrl);
                    this.showStatus(`连接成功！${protocolInfo}`, 'success');
                    client.end();
                    resolve(true);
                });

                client.on('error', (error) => {
                    clearTimeout(timeout);
                    const errorMsg = this.getErrorMessage(error, brokerUrl);
                    this.showStatus(`连接失败: ${errorMsg}`, 'error');
                    client.end();
                    resolve(false);
                });

                // 监听连接关闭事件
                client.on('close', () => {
                    clearTimeout(timeout);
                });
            });

        } catch (error) {
            this.showStatus(`测试失败: ${error.message}`, 'error');
            return false;
        }
    }

    // 获取协议信息
    getProtocolInfo(brokerUrl) {
        if (brokerUrl.startsWith('mqtts://') || brokerUrl.startsWith('wss://')) {
            return '(TLS/SSL加密连接)';
        } else if (brokerUrl.startsWith('ws://')) {
            return '(WebSocket连接)';
        }
        return '(TCP连接)';
    }

    // 获取更友好的错误信息
    getErrorMessage(error, brokerUrl) {
        const errorMsg = error.message || error.toString();
        
        // 常见错误类型处理
        if (errorMsg.includes('ECONNREFUSED')) {
            return `连接被拒绝，请检查Broker地址和端口: ${brokerUrl}`;
        } else if (errorMsg.includes('ENOTFOUND')) {
            return `无法解析主机名，请检查网络连接和Broker地址`;
        } else if (errorMsg.includes('UNAUTHORIZED')) {
            return `认证失败，请检查用户名和密码`;
        } else if (errorMsg.includes('TLS')) {
            return `TLS握手失败，请检查证书配置`;
        }
        
        return errorMsg;
    }

    async loadMQTT() {
        return new Promise((resolve, reject) => {
            if (typeof mqtt !== 'undefined') {
                resolve();
                return;
            }

            const script = document.createElement('script');
            script.src = 'https://unpkg.com/mqtt/dist/mqtt.min.js';
            script.onload = resolve;
            script.onerror = () => reject(new Error('MQTT.js加载失败'));
            document.head.appendChild(script);
        });
    }

    showStatus(message, type = 'info') {
        const statusElement = document.getElementById('connection-status') || document.getElementById('save-status');
        if (!statusElement) return;

        statusElement.textContent = message;
        statusElement.className = `status-message ${type}`;
        statusElement.style.display = 'block';

        // 5秒后自动隐藏
        setTimeout(() => {
            statusElement.style.display = 'none';
        }, 5000);
    }

    getConfig() {
        return this.config;
    }
}

// 页面加载完成后初始化配置管理器
document.addEventListener('DOMContentLoaded', () => {
    window.configManager = new ConfigManager();
});